package cn.ty.comm.dict;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author summit
 * @since 2021/7/22 16:48
 */
public class Test
{

	public static void main(String[] args) {
		List<Person> personList = new ArrayList<>();
		personList.add(new Person("one", 10));
		personList.add(new Person("two", 20));
		personList.add(new Person("three", 30));
		//这两的name值重复
		personList.add(new Person("four", 40));
		personList.add(new Person("four", 42));

		System.out.println("利用Collectors.toCollection和TreeSet去重:");

		//利用TreeSet原理去重(TreeSet内部使用的是TreeMap，使用指定Comparator比较元素，如果元素相同，则新元素代替旧元素)
		List<Person> collect = new ArrayList<>(personList.stream()
				.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName)))));
		personList.stream()
				.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))))
				.stream()
				.forEach(System.out::println); //打印

	}
}
